import { cadAppLog, CMEVENTS, FeatureManager } from '@amcax/base';
import { userEvents } from '@app-cad/module';
import { wsApi } from '@app-cad/server';
import { Box, TextField } from '@mui/material';
import { useEffect, useState } from 'react';

type VersionInfo = {
  project: {
    name: string;
    version: string;
    build_number: string;
    build_time: string;
  };
  deps: {
    amcax: string;
    amcax_storage: string;
  };
};

export default function DefaultVersionPanel(props?: any) {
  cadAppLog('DefaultVersionPanel', props);

  const [params, setParams] = useState({});

  useEffect(() => {
    userEvents.emit(CMEVENTS.RIGHT_PANEL_TOGGLE, { open: true, width: 300 });

    loadNextcoreInfo();

    return () => {
      userEvents.emit(CMEVENTS.RIGHT_PANEL_TOGGLE, { open: false, width: 300 });
    };
  }, []);

  const loadNextcoreInfo = async () => {
    // get data
    await wsApi.getVersionInfo().then((data) => {
      if (data) {
        updateVersion(data);
      } else {
        updateVersion();
      }
    });
  };

  const updateVersion = (data?: VersionInfo) => {
    if (data) {
      setParams({
        CAD_Web: FeatureManager.getFeatureValue('version'),
        NEXT_CORE_VERSION: data.project.version,
        NEXT_CORE_BUILD_NUMBER: data.project.build_number,
        NEXT_CORE_BUILD_TIME: data.project.build_time,
        DEP_AMCAX_VERSION: data.deps.amcax,
        DEP_AMX_STORAGE_VERSION: data.deps.amcax_storage,
      });
    } else {
      setParams({
        CAD_Web: FeatureManager.getFeatureValue('version'),
      });
    }
  };

  return (
    <>
      {
        <Box sx={{ mt: '10px', overflowY: 'auto', width: '100%' }}>
          {params ? (
            Object.entries(params).map(([key, value]) => {
              return (
                <TextField
                  label={key}
                  key={key}
                  sx={{ width: '100%', mt: '10px' }}
                  value={value}
                  size='small'
                />
              );
            })
          ) : (
            <></>
          )}
        </Box>
      }
    </>
  );
}
